<!DOCTYPE html>
<html lang="en">
	<head>
		<title>three.js webgpu - ambient occlusion</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="example.css">
	</head>
	<body>

		<div id="info">
			<a href="https://threejs.org/" target="_blank" rel="noopener" class="logo-link"></a>

			<div class="title-wrapper">
				<a href="https://threejs.org/" target="_blank" rel="noopener">three.js</a><span>AO</span>
			</div>

			<small>
				Ambient Occlusion based on GTAO.<br />
				<a href="https://skfb.ly/oCnNx" target="_blank" rel="noopener">Minimalistic Modern Bedroom</a> by
				<a href="https://sketchfab.com/dylanheyes" target="_blank" rel="noopener">dylanheyes</a> is licensed under <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">Creative Commons Attribution</a>.
			</small>
		</div>

		<script type="importmap">
			{
				"imports": {
					"three": "../build/three.webgpu.js",
					"three/webgpu": "../build/three.webgpu.js",
					"three/tsl": "../build/three.tsl.js",
					"three/addons/": "./jsm/"
				}
			}
		</script>

		<script type="module">

			import * as THREE from 'three/webgpu';
			import { sample, pass, mrt, screenUV, normalView, velocity, vec3, vec4, directionToColor, colorToDirection, colorSpaceToWorking, builtinAOContext } from 'three/tsl';
			import { ao } from 'three/addons/tsl/display/GTAONode.js';
			import { traa } from 'three/addons/tsl/display/TRAANode.js';

			import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
			import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
			import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
			import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';

			import { Inspector } from 'three/addons/inspector/Inspector.js';

			let camera, scene, renderer, postProcessing, controls;

			let aoPass, traaPass, transparentMesh;

			const params = {
				samples: 16,
				distanceExponent: 1,
				distanceFallOff: 1,
				radius: 0.25,
				scale: 1,
				thickness: 1,
				aoOnly: false,
				transparentOpacity: 0.3
			};

			init();

			async function init() {

				camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 0.1, 50 );
				camera.position.set( 1, 1.3, 5 );

				scene = new THREE.Scene();

				renderer = new THREE.WebGPURenderer();
				renderer.setPixelRatio( window.devicePixelRatio );
				renderer.setSize( window.innerWidth, window.innerHeight );
				renderer.setAnimationLoop( animate );
				renderer.inspector = new Inspector();
				document.body.appendChild( renderer.domElement );

				await renderer.init();

				// controls

				controls = new OrbitControls( camera, renderer.domElement );
				controls.target.set( 0, 0.5, - 1 );
				controls.update();
				controls.enablePan = false;
				controls.enableDamping = true;
				controls.minDistance = 2;
				controls.maxDistance = 8;

				// environment

				const environment = new RoomEnvironment();
				const pmremGenerator = new THREE.PMREMGenerator( renderer );

				scene.background = new THREE.Color( 0x666666 );
				scene.environment = pmremGenerator.fromScene( environment ).texture;
				environment.dispose();
				pmremGenerator.dispose();

				// post-processing

				postProcessing = new THREE.PostProcessing( renderer );

				// pre-pass

				const prePass = pass( scene, camera ).toInspector( 'Normal', ( inspectNode ) => colorSpaceToWorking( inspectNode, THREE.SRGBColorSpace ) );
				prePass.name = 'Pre-Pass';
				prePass.transparent = false;

				prePass.setMRT( mrt( {
					output: directionToColor( normalView ),
					velocity: velocity
				} ) );

				const prePassNormal = sample( ( uv ) => {

					return colorToDirection( prePass.getTextureNode().sample( uv ) );

				} );

				const prePassDepth = prePass.getTextureNode( 'depth' ).toInspector( 'Depth', () => prePass.getLinearDepthNode() );
				const prePassVelocity = prePass.getTextureNode( 'velocity' ).toInspector( 'Velocity' );

				// pre-pass - bandwidth optimization

				const normalTexture = prePass.getTexture( 'output' );
				normalTexture.type = THREE.UnsignedByteType;

				// scene pass

				const scenePass = pass( scene, camera ).toInspector( 'Color' );

				// ao

				aoPass = ao( prePassDepth, prePassNormal, camera ).toInspector( 'GTAO', ( inspectNode ) => inspectNode.r );
				aoPass.resolutionScale = 0.5; // running AO in half resolution is often sufficient
				aoPass.useTemporalFiltering = true;

				const aoPassOutput = aoPass.getTextureNode();

				// scene context

				scenePass.contextNode = builtinAOContext( aoPassOutput.sample( screenUV ).r );

				// final output + traa

				traaPass = traa( scenePass, prePassDepth, prePassVelocity, camera );
				traaPass.useSubpixelCorrection = false;

				postProcessing.outputNode = traaPass;

				// models

				const dracoLoader = new DRACOLoader();
				dracoLoader.setDecoderPath( 'jsm/libs/draco/' );
				dracoLoader.setDecoderConfig( { type: 'js' } );
				const loader = new GLTFLoader();
				loader.setDRACOLoader( dracoLoader );
				loader.setPath( 'models/gltf/' );

				const gltf = await loader.loadAsync( 'minimalistic_modern_bedroom.glb' );

				const model = gltf.scene;
				model.position.set( 0, 1, 0 );
				scene.add( model );

				//

				transparentMesh = new THREE.Mesh( new THREE.PlaneGeometry( 1.8, 2 ), new THREE.MeshStandardNodeMaterial( { transparent: true, opacity: params.transparentOpacity } ) );
				transparentMesh.position.z = 0;
				transparentMesh.position.y = 0.5;
				transparentMesh.visible = false;
				scene.add( transparentMesh );

				// events

				window.addEventListener( 'resize', onWindowResize );

				//

				const gui = renderer.inspector.createParameters( 'Settings' );
				gui.add( params, 'samples', 4, 32, 1 ).onChange( updateParameters );
				gui.add( params, 'distanceExponent', 1, 2 ).onChange( updateParameters );
				gui.add( params, 'distanceFallOff', 0.01, 1 ).onChange( updateParameters );
				gui.add( params, 'radius', 0.1, 1 ).onChange( updateParameters );
				gui.add( params, 'scale', 0.01, 2 ).onChange( updateParameters );
				gui.add( params, 'thickness', 0.01, 2 ).onChange( updateParameters );
				gui.add( aoPass, 'useTemporalFiltering' ).name( 'temporal filtering' );
				gui.add( transparentMesh, 'visible' ).name( 'show transparent mesh' );
				gui.add( params, 'transparentOpacity', 0, 1, 0.01 ).name( 'transparent opacity' ).onChange( updateParameters );
				gui.add( params, 'aoOnly' ).onChange( ( value ) => {

					if ( value === true ) {

						postProcessing.outputNode = vec4( vec3( aoPass.r ), 1 );

					} else {


						postProcessing.outputNode = traaPass;

					}

					postProcessing.needsUpdate = true;

				} );

			}

			function updateParameters() {

				aoPass.samples.value = params.samples;
				aoPass.distanceExponent.value = params.distanceExponent;
				aoPass.distanceFallOff.value = params.distanceFallOff;
				aoPass.radius.value = params.radius;
				aoPass.scale.value = params.scale;
				aoPass.thickness.value = params.thickness;

				transparentMesh.material.opacity = params.transparentOpacity;

			}

			function onWindowResize() {

				const width = window.innerWidth;
				const height = window.innerHeight;

				camera.aspect = width / height;
				camera.updateProjectionMatrix();

				renderer.setSize( width, height );

			}

			function animate() {

				controls.update();

				postProcessing.render();

			}

		</script>
	</body>
</html>
